#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int fd = open("book.dat", O_RDWR | O_CREAT, 0644);
    struct flock lock = {F_WRLCK, SEEK_SET, 0, 0, getpid()};

    // 确保文件存在
    if (fd == -1)
    {
        perror("open");
        exit(1);
    }

    // 尝试加写锁
    if (fcntl(fd, F_SETLK, &lock) == -1)
    {
        printf("File is already locked!\n");
        exit(1);
    }
    printf("Write lock acquired. Press Enter to exit...\n");
    getchar();
    return 0;
}